package com.zzzyh.forumsystemclient.services.impl;

import com.alibaba.fastjson.JSON;
import com.zzzyh.forumsystemclient.common.AppResult;
import com.zzzyh.forumsystemclient.common.Constant;
import com.zzzyh.forumsystemclient.common.ResultCode;
import com.zzzyh.forumsystemclient.dao.RoleMapper;
import com.zzzyh.forumsystemclient.dao.UserMapper;
import com.zzzyh.forumsystemclient.exception.AppException;
import com.zzzyh.forumsystemclient.model.LoginUser;
import com.zzzyh.forumsystemclient.model.Role;
import com.zzzyh.forumsystemclient.model.User;
import com.zzzyh.forumsystemclient.services.IUserService;
import com.zzzyh.forumsystemclient.utils.JwtUtils;
import com.zzzyh.forumsystemclient.utils.MD5Util;
import com.zzzyh.forumsystemclient.utils.StringUtil;
import com.zzzyh.forumsystemclient.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
/**
 * @author 郑雨杭
 * @create 2025/5/28 - 15:13
 */
@Slf4j
@Service
public class UserServicesImpl implements IUserService{
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void createUser(User user) {
        if(user == null || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getPassword())
                || StringUtil.isEmpty(user.getNickname())) {
            log.warn(ResultCode.FAILED_PARAM_ERROR.getMessage());
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAM_ERROR));
        }
        User userExist = userMapper.selectByUsername(user.getUsername());
        if(userExist != null) {
            log.warn(ResultCode.FAILED_USER_EXIST.getMessage());
            throw new AppException(AppResult.failed(ResultCode.FAILED_USER_EXIST));
        }
        user.setSalt(UUIDUtil.getUUID_32());
        user.setPassword(Constant.PWD_ENCODER_PREFIX+MD5Util.md5BySalt(user.getPassword(), user.getSalt()));
        int row = userMapper.insertSelective(user);
        if(row != 1) {
            log.warn(ResultCode.FAILED_USER_ADD_ERROR.getMessage());
            throw new AppException(AppResult.failed(ResultCode.FAILED_USER_ADD_ERROR));
        }
        log.info("用户{}新增成功", user.getUsername());
    }

    public String login(User user){
        if(user == null || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getPassword())) {
            log.warn(ResultCode.FAILED_PARAM_ERROR.getMessage());
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAM_ERROR));
        }
        log.info("用户{}登录", user);
        user.setPassword(MD5Util.md5BySalt(user.getPassword(), user.getSalt()));
        log.info("用户{}登录", user);
        UsernamePasswordAuthenticationToken authenticationToken= new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        if(authentication == null)
            throw new RuntimeException("登录失败");
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        loginUser.getUser().setSalt( null);
        loginUser.getUser().setPassword(null);
        Role  role = roleMapper.selectByUserId(loginUser.getUser().getId());
        loginUser.getUser().setRole(role);
        String jsonString = JSON.toJSONString(loginUser);
        return JwtUtils.generateToken(jsonString);
    }

    @Override
    public String selectSaltByUsername(String username) {
        return userMapper.selectSaltByUsername(username);
    }

    @Override
    public User selectUserByUserId(Long userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        Role  role = roleMapper.selectByUserId(user.getId());
        user.setRole(role);
         return user;
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }
}
